## Author: 	M. Orloswki
## Project:	Coalition Probabilities
## Content:	Function to compute the predicted probability of government participation 
##			for each party in a formation opportunity
## Notes: 	- Consider optional splitting between incumbent and alternative coalition

getPrIngov <- function(dat, prob.var, comp.var, pty.sep
					, pty.out = "party_abbr"
					, prob.out = "pr_ingov"){
	##
	## This function computes the predicted probability for each party in a
	## formation opportunity to be in government based on the predicted probabilities
	## for each potential government.
	##
	## Args.:
	##	dat:		A data frame with porential governments from one formation 
	## 				opportunity and the predicted probability for it to be realized
	##	prob.var:	Integer or character value indicating the column with predicted 
	## 				probabilities
	##	comp.var: 	Integer or character value indicating the column with information 
	## 				on the partisan composition of the potential government
	##	pty.sep: 	A character value giving the separator used to separate parties 
	##				in comp.var
	## 	pty.out: 	A character value indicating the name for the party id variable
	##				in the output data frame. Default is "party_abbr"
	## 	prob.out: 	A character value indicating the name for the predicted probability
	##				variable in the output data frame. Default is "pr_ingov"
	##
	## Returns:
	##	A data frame with two columns: 
	##		pty.out: party ids
	##		prob.out: predicted probability of government participation
	##

	# get parties
	pty_lst <- strsplit(as.character(dat[[comp.var]]), pty.sep)
	ptys <- unique(unlist(pty_lst))
	
	# Sum predicted probabilities over parties
	np <- length(ptys)
	pr_ingov <- rep(NA, length(ptys))

	for( i in 1:np ){
		p <- ptys[i]
		contains_p <- sapply(pty_lst, function(x) p %in% x)
		pr_ingov[i] <- sum(dat[[prob.var]][which(contains_p)])
	}
	
	out <- data.frame(ptys, pr_ingov)
	names(out) <- c(pty.out, prob.out)
	
	return(out)

}